package com.hjm.project.agentInfo.profitSbOrder.service.impl;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.hjm.common.utils.*;
import com.hjm.common.utils.poi.ExcelUtil;
import com.hjm.common.utils.trade.LoFunction;
import com.hjm.framework.config.CustomConfig;
import com.hjm.framework.web.domain.AjaxResult;
import java.math.BigDecimal;
import java.util.*;

import com.google.common.collect.Maps;
import com.hjm.common.exception.BusinessException;
import com.hjm.project.agentInfo.profitSbOrder.domain.AgentPaiTemplate;
import com.hjm.project.agentInfo.profitSbOrder.domain.ProfitSbOrderExport;
import com.hjm.project.agentInfo.profitSbOrder.utils.PublicTypeUtils;
import com.hjm.project.job.task.domain.JobTask;
import com.hjm.project.job.task.mapper.JobTaskMapper;
import com.hjm.project.job.task.service.IJobTaskService;
import com.yxhd.encrypt.EncryptUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.hjm.project.agentInfo.profitSbOrder.mapper.ProfitSbOrderMapper;
import com.hjm.project.agentInfo.profitSbOrder.domain.ProfitSbOrder;
import com.hjm.project.agentInfo.profitSbOrder.service.IProfitSbOrderService;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 分润单号Service业务层处理
 *
 * @author LOVE
 * @date 2020-11-27
 */
@Service
public class ProfitSbOrderServiceImpl implements IProfitSbOrderService
{
    @Resource
    private ProfitSbOrderMapper profitSbOrderMapper;

    @Resource
    private IJobTaskService jobTaskService;

    @Resource
    private JobTaskMapper jobTaskMapper;

    private static LoFunction lo = new LoFunction();

    /**
     * 查询分润单号
     *
     * @param ordernumber 分润单号ID
     * @return 分润单号
     */
    @Override
    public ProfitSbOrder selectProfitSbOrderById(String ordernumber)
    {
        return profitSbOrderMapper.selectProfitSbOrderById(ordernumber);
    }

    /**
     * 查询分润单号列表
     *
     * @param profitSbOrder 分润单号
     * @return 分润单号
     */
    @Override
    public List<ProfitSbOrder> selectProfitSbOrderList(ProfitSbOrder profitSbOrder)
    {
        return profitSbOrderMapper.selectProfitSbOrderList(profitSbOrder);
    }

    /**
     * 新增分润单号
     *
     * @param profitSbOrder 分润单号
     * @return 结果
     */
    @Override
    public int insertProfitSbOrder(ProfitSbOrder profitSbOrder)
    {
        return profitSbOrderMapper.insertProfitSbOrder(profitSbOrder);
    }

    /**
     * 修改分润单号
     *
     * @param profitSbOrder 分润单号
     * @return 结果
     */
    @Override
    public int updateProfitSbOrder(ProfitSbOrder profitSbOrder)
    {
        return profitSbOrderMapper.updateProfitSbOrder(profitSbOrder);
    }

    /**
     * 删除分润单号对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteProfitSbOrderByIds(String ids)
    {
        return profitSbOrderMapper.deleteProfitSbOrderByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除分润单号信息
     *
     * @param ordernumber 分润单号ID
     * @return 结果
     */
    @Override
    public int deleteProfitSbOrderById(String ordernumber)
    {
        return profitSbOrderMapper.deleteProfitSbOrderById(ordernumber);
    }

    @Override
    @Async
    public AjaxResult exportDetailExcel(ProfitSbOrder profitSbOrder, String createBy) throws Exception {
        try {
            //审核单信息
            profitSbOrder = profitSbOrderMapper.selectProfitSbOrderById(profitSbOrder.getOrdernumber());
            //导出的数据
            List<Map<String, Object>> detailList = profitSbOrderMapper.selectAgentPaidByOrderNumber(profitSbOrder.getOrdernumber());

            Map<String, List<Map<String, Object>>> exportMap = Maps.newHashMap();

            String nature = "对公";
            String[] names = {"SETTLE_SERIAL","ORDERNUMBER","AGENT_NUM","AGENT_NAME","AUDITDATE",
                    "CYCLE","BANK_HEADNAME","BANK_NAME","SCREEN_NAME","SCREEN_NUM","MONEY","STATUS","AGENT_TYPE"};
            if ("2".equals(profitSbOrder.getOrdertype())){
                nature = "对私";
                names = new String[]{"SETTLE_SERIAL","ORDERNUMBER","AGENT_NUM","AGENT_NAME","AUDITDATE",
                        "CYCLE","BANK_NAME","BANK_HEADNAME","SCREEN_NAME","SCREEN_NUM","MONEY","STATUS","AGENT_TYPE"};
            }
            String type = "";
            //组装数据
            for (Map<String, Object> detail : detailList) {
                if (StringUtils.isNotEmpty(String.valueOf(detail.get("AGENT_TYPE"))) && StringUtils.isEmpty(type)){
                    switch (String.valueOf(detail.get("AGENT_TYPE"))){
                        case "0": type="传统"; break;
                        case "4": type="电签";break;
                    }
                }
                //解密卡号
                if(StringUtils.isNotEmpty(String.valueOf(detail.get("SCREEN_NUM")))){
                    detail.put("SCREEN_NUM", detail.get("SCREEN_NUM") != null ? EncryptUtils.getDecrypt(detail.get("SCREEN_NUM").toString()) : "");
                }
                //周期
                if (detail.get("CYCLE") != null){
                    switch (detail.get("CYCLE").toString()){
                        case "0":detail.put("CYCLE","日返");break;
                        case "1":detail.put("CYCLE","月返");break;
                    }
                }
                //出款状态
                if(detail.get("STATUS") != null){
                    switch (detail.get("STATUS").toString()){
                        case "0":detail.put("STATUS","待处理");break;
                        case "1":detail.put("STATUS","出款成功");break;
                        case "-3":detail.put("STATUS","冻结");break;
                        case "-1":detail.put("STATUS","已上送");break;
                        case "-2":
                        default:detail.put("STATUS","出款失败");break;
                    }
                }
                //机具类型
                if(detail.get("AGENT_TYPE") != null){
                    switch (detail.get("AGENT_TYPE").toString()){
                        case "0":detail.put("AGENT_TYPE","传统");break;
                        case "4":detail.put("AGENT_TYPE","电签");break;
                        default:detail.put("AGENT_TYPE","未知");break;
                    }
                }
                //类型
                String profitType;
                switch (detail.get("PROFIT_TYPE").toString()){
                    case "0":profitType = "代理商直推分润";break;
                    case "1":profitType = "团队分润";break;
                    case "2":profitType = "引流奖励";break;
                    case "3":profitType = "一段达标返现";break;
                    case "4":profitType = "二段达标返现";break;
                    case "5":profitType = "三段达标返现";break;
                    case "6":profitType = "提现奖励";break;
                    case "11":profitType = "自采购奖励(4元)";break;
                    case "12":profitType = "团员采购奖励(8元)";break;
                    case "13":profitType = "云闪付返现奖励";break;
                    case "14":profitType = "引流奖励人员";break;
                    case "15":profitType = "引流人员入伙补差";break;
                    case "16":profitType = "采购奖励政策";break;
                    case "17":profitType = "增量奖励";break;
                    case "18":profitType = "交易量新增一千万返现";break;
                    case "19":profitType = "雏鹰计划奖励";break;
                    case "20":profitType = "210激团奖（团长引流奖励 A）";break;
                    case "21":profitType = "传统引流奖励";break;
                    case "22":profitType = "分润税奖励";break;
                    case "24":profitType = "底薪计划";break;
                    case "25":profitType = "流量卡返现";break;
                    case "26":profitType = "机具尾款返现";break;
                    case "27":profitType = "采购人奖励";break;
                    default:profitType = "未知";break;
                }
                List<Map<String, Object>> mapList = exportMap.get(profitType);
                if (mapList == null){
                    mapList = new ArrayList<>();
                    exportMap.put(profitType,mapList);
                }
                mapList.add(detail);
            }
            LinkedHashMap<String, String> titleMap = new LinkedHashMap<>();
            titleMap.put("SETTLE_SERIAL","流水号");
            titleMap.put("ORDERNUMBER","审核单号");
            titleMap.put("AGENT_NUM","服务商编号");
            titleMap.put("AGENT_NAME","服务商名称");
            titleMap.put("AUDITDATE","生成日期");
            titleMap.put("CYCLE","周期");
            titleMap.put("SCREEN_NAME","结算人");
            titleMap.put("BANK_HEADNAME","总行名称");
            titleMap.put("BANK_NAME","开户行名称");
            titleMap.put("SCREEN_NUM","结算卡");
            titleMap.put("MONEY","结算金额");
            titleMap.put("STATUS","出款状态");
            titleMap.put("AGENT_TYPE","机具类型");


            //计算合计
            for (String key : exportMap.keySet()) {
                HashMap total = Maps.newHashMap();
                total.put("SETTLE_SERIAL","合计");
                total.put("MONEY",new BigDecimal(0));
                total.put("STATUS",0);
                List<Map<String, Object>> mapList = exportMap.get(key);
                for (Map<String, Object> map : mapList) {
                    total.put("MONEY", ((BigDecimal)total.get("MONEY")).add(((BigDecimal) map.get("MONEY"))));
                    total.put("STATUS", ((int)total.get("STATUS"))+1);
                }
                mapList.add(total);
            }
            Map<String, Object> workBookMap = null;
            if(exportMap.containsKey("代理商直推分润")){
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("代理商直推分润"), titleMap, "代理商直推分润");
            }
            if(exportMap.containsKey("团队分润")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("团队分润"), titleMap, "团队分润");
            }
            if(exportMap.containsKey("引流奖励")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("引流奖励"), titleMap, "引流奖励");
            }
            if(exportMap.containsKey("一段达标返现")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("一段达标返现"), titleMap, "一段达标返现");
            }
            if(exportMap.containsKey("二段达标返现")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("二段达标返现"), titleMap, "二段达标返现");
            }
            if(exportMap.containsKey("三段达标返现")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("三段达标返现"), titleMap, "三段达标返现");
            }
            if(exportMap.containsKey("提现奖励")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("提现奖励"), titleMap, "提现奖励");
            }
            if(exportMap.containsKey("自采购奖励(4元)")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("自采购奖励(4元)"), titleMap, "自采购奖励(4元)");
            }
            if(exportMap.containsKey("团员采购奖励(8元)")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("团员采购奖励(8元)"), titleMap, "团员采购奖励(8元)");
            }
            if(exportMap.containsKey("云闪付返现奖励")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("云闪付返现奖励"), titleMap, "云闪付返现奖励");
            }
            if(exportMap.containsKey("引流奖励人员")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("引流奖励人员"), titleMap, "引流奖励人员");
            }
            if(exportMap.containsKey("引流人员入伙补差")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("引流人员入伙补差"), titleMap, "引流人员入伙补差");
            }
            if(exportMap.containsKey("采购奖励政策")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("采购奖励政策"), titleMap, "采购奖励政策");
            }
            if(exportMap.containsKey("增量奖励")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("增量奖励"), titleMap, "增量奖励");
            }
            if(exportMap.containsKey("交易量新增一千万返现")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("交易量新增一千万返现"), titleMap, "交易量新增一千万返现");
            }
            if(exportMap.containsKey("雏鹰计划奖励")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("雏鹰计划奖励"), titleMap, "雏鹰计划奖励");
            }
            if(exportMap.containsKey("210激团奖（团长引流奖励 A）")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("210激团奖（团长引流奖励 A）"), titleMap, "210激团奖（团长引流奖励 A）");
            }
            if(exportMap.containsKey("传统引流奖励")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("传统引流奖励"), titleMap, "传统引流奖励");
            }
            if(exportMap.containsKey("分润税奖励")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("分润税奖励"), titleMap, "分润税奖励");
            }
            if(exportMap.containsKey("底薪计划")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("底薪计划"), titleMap, "底薪计划");
            }

            if(exportMap.containsKey("流量卡返现")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("流量卡返现"), titleMap, "流量卡返现");
            }

            if(exportMap.containsKey("机具尾款返现")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("机具尾款返现"), titleMap, "机具尾款返现");
            }
            if(exportMap.containsKey("采购人奖励")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("采购人奖励"), titleMap, "采购人奖励");
            }
//            if(exportMap.containsKey("高签分润")) {
//                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("高签分润"), titleMap, "高签分润");
//            }
            if(exportMap.containsKey("未知")) {
                workBookMap = ExportExcelUtil.exportListExcelClearExcel(workBookMap, exportMap.get("未知"), titleMap, "未知");
            }
            if (workBookMap != null){
                String fileName = DateUtils.getSimpleDateTimeMillisecond() + nature + "_" + type + ".xlsx";
                ExportExcelUtil.exportExcel(workBookMap, fileName);

                JobTask jobTask=new JobTask();
                jobTask.setOperatorType(Long.parseLong("12"));
                jobTask.setFileName(fileName);
                jobTask.setOperatorContent("分润审核单明细");
                jobTask.setSource(Long.parseLong("0"));
                jobTask.setCreateBy(createBy);
                jobTask.setCreateTime(DateUtils.getNowDate());
                jobTask.setStatus(Long.parseLong("2"));
                jobTask.setIsDelete(Long.parseLong("0"));
                jobTaskMapper.insertJobTask(jobTask);
                jobTask.setUpdateBy(createBy);
                jobTask.setUpdateTime(DateUtils.getNowDate());
                jobTask.setStatus(Long.parseLong("0"));
                jobTaskMapper.updateJobTask(jobTask);
                return AjaxResult.success(fileName);
            }
            return AjaxResult.error("审核单无数据");
        } catch (Exception e) {
            e.printStackTrace();
            throw  e;
        }
    }

    @Override
    public List<Map<String, Object>> getDateOrdernumber(Map<String, Object> params) {
        return profitSbOrderMapper.getDateOrdernumber(params);
    }

    @Override
    public List<Map<String, Object>> getUnPayPageList(Map<String, Object> params) {
        return profitSbOrderMapper.getUnPayPageList(params);
    }
    @Override
    public Map<String, Object> getUnPayPageListSum(Map<String, Object> params) {
        return profitSbOrderMapper.getUnPayPageListSum(params);
    }

    /**
     * 导出分润出款明细
     * @param params 分润单号
     * @param addMan
     */
    @Override
    @Async
    public void getUnPayPageExport(Map<String, Object> params,String addMan) {
        List<ProfitSbOrderExport> list =  profitSbOrderMapper.getUnPayPageExport(params);
        com.hjm.common.utils.poi.ExcelUtil<ProfitSbOrderExport> util = new ExcelUtil<>(ProfitSbOrderExport.class);
        jobTaskService.asyncDownLoad("payList",Long.parseLong("9"),"分润出款明细",addMan,list,util);
    }

    @Override
    public AjaxResult saveOrder(Map<String, Object> params) {
        params.put("indate", Utils.formateDate(0));
        params.put("intime", Utils.formateDate(3));
        params.put("remittance_way",1);
        int result=profitSbOrderMapper.saveOrder(params);
        return  result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public int examineAgent(String ordernumber) {
        return profitSbOrderMapper.examineAgent(ordernumber);
    }

    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void saveBatchOrder(Map params, String[] ids, int type) {
        LogUtils.logInfo("进入功能填单-------------------------->" + ids);
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("ordernumber",params.get("ordernumber"));
        //查询订单信息
        Map<String, Object> orderMap = profitSbOrderMapper.getOrderOne(paramMap);
        //订单性质 对公 对私
        String orderType = String.valueOf(orderMap.get("ORDERTYPE"));
        paramMap.put("orderType",orderType);
        //单笔最大金额限制
        BigDecimal tranddelMax1=new BigDecimal(CustomConfig.getTranddelMax());
        List<Map<String,Object>> upList = new ArrayList<>();
        //限制条件（未出款）
        paramMap.put("settle_state", 0);
        //type 0-填单、1-一键填单
        if (type==0){
            paramMap.put("ids",ids);
            upList=profitSbOrderMapper.getUnPayListById(paramMap);
            LogUtils.logInfo("开始进行填单-------------------------->");
        }else if (type==1){
            LogUtils.logInfo("开始进行一键填单-------------------------->");
            String hiddenFormValue = String.valueOf(params.get("hiddenForm"));
            if (StringUtils.isNotBlank(hiddenFormValue)){
                hiddenFormValue = hiddenFormValue.replaceAll("&amp;","&");
                for (String s : hiddenFormValue.split("&")) {
                    String[] split = s.split("=");
                    if (split.length == 2){
                        paramMap.put(split[0],split[1]);
                    }
                }
            }
            upList=profitSbOrderMapper.getUnPayList(paramMap);
        }
        LogUtils.logInfo("---------------------------->" + paramMap);
        LogUtils.logInfo("upList.Size()--------------->" + upList.size());
        if(upList.size() == 0){
            //不存在满足条件的出款数据
            LogUtils.logInfo("没有数据填单结束-------------------------->");
            return;
        }

        //金额为0的不填单
        for (Map<String, Object> result : upList) {
            BigDecimal b = new BigDecimal("0.00");
            BigDecimal money = new BigDecimal(String.valueOf(result.get("MONEY")));
            int i = money.compareTo(b);
            if ( i == -1 || i == 0) {
                LogUtils.logInfo("金额 <= 0 填单结束-------------------------->");
                return;
            }
        }


        List<String> ableIntList = new ArrayList<>();
        for (Map<String,Object> tmp : upList){
            //判断选择的出款数据的性质（对公，对私），是否满足订单性质
            String accountType= String.valueOf(tmp.get("NATURE"));
            if (orderType.equals(accountType)){
                //校验金额是否超过二十万
                BigDecimal tmpMoney=new BigDecimal(String.valueOf(tmp.get("MONEY")));
                if (tmpMoney.compareTo(tranddelMax1) < 1){
                    //不大于二十万
                    ableIntList.add(String.valueOf(tmp.get("SETTLE_SERIAL")));
                }
            }
        }
        //更新出款数据订单号
        List<List<String>> partition = Lists.partition(ableIntList, 500);
        for (List<String> list : partition) {
            paramMap.put("ableIntList",list);
            profitSbOrderMapper.updateMerPaidOrderTwo(paramMap);
        }
        //更新订单信息
        profitSbOrderMapper.updateOrderInfoByDb(paramMap);
        LogUtils.logInfo("处理完成-------------------------->");
    }

    /**
     * 一键填单
     * @Param [params, ids, type]
     * @Return void
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAllOrder(Map params) {
        LogUtils.logInfo("开始一键填单-------------------------->");
        //要填充的订单号
        String ordernumber = params.get("ordernumber").toString();
        //查询订单信息
        Map<String, Object> orderMap = profitSbOrderMapper.getOrderOne(params);
        //不可使用已建单订单
        if (!"2".equals(orderMap.get("STATE").toString())) {
            LogUtils.logInfo("当前订单已使用,请使用新订单:" + ordernumber);
            throw new BusinessException("当前订单已使用,请使用新订单:" + ordernumber);
        }
        //订单账户类型 ordertype 1=对公 2=对私
        String nature = orderMap.get("ORDERTYPE").toString();

        //获取和订单账户类型一致的出款信息
        params.put("status","0");                   //未处理状态
        params.put("nature",nature);                //账户类型 （1：对公  2：对私 ）
        params.put("no_agent_num","100000000");     //过滤服务商
        params.put("min_money","0");                //最小金额
        params.put("max_money","500000");           //最大金额
        List<Map<String,Object>> unPayList = profitSbOrderMapper.getUnPayAllList(params);
        if (CollectionUtils.isEmpty(unPayList)) {
            LogUtils.logInfo("未获取到出款信息,查询参数:" + params);
            throw new BusinessException("未获取到出款信息");
        }
        //统计当前批次流水总额
        Map unPayAllSum = profitSbOrderMapper.getUnPayAllSum(params);

        //更新出款信息订单号
        Map updateOrder = new HashMap();
        updateOrder.put("ordernumber",ordernumber);          //订单号
        List<List<Map<String,Object>>> lists = this.getSumArrayList(unPayList);
        updateOrder.put("list",lists);                   //出款流水
        int k = profitSbOrderMapper.updateMerPaidOrderTwoList(updateOrder);
        if (k <= 0) {
            throw new BusinessException("更新出款表订单失败");
        }

        //更新订单信息
        ProfitSbOrder profitSbOrder = new ProfitSbOrder();
        profitSbOrder.setOrdernumber(ordernumber);
        profitSbOrder.setPayMoney(Double.valueOf(unPayAllSum.get("MONEY").toString()));
        profitSbOrder.setSumtrade(Long.parseLong(unPayAllSum.get("AGENT_COUNT").toString()));
        profitSbOrder.setSumcount(Long.parseLong(unPayAllSum.get("COUNTS").toString()));
        profitSbOrder.setState(Long.parseLong("3"));
        int i = profitSbOrderMapper.updateProfitSbOrder(profitSbOrder);
        if (i <= 0) {
            throw new BusinessException("更新订单失败");
        }
        LogUtils.logInfo("填单处理成功-------------------------->" + unPayList.size());
    }

    @Override
    public int saveBatchOrder(String ordernumber, String[] ids, int type) throws Exception {
        int result=0;
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("ordernumber",ordernumber);
        //查询订单信息
        Map<String, Object> orderMap = profitSbOrderMapper.getOrderOne(paramMap);
        if (null==orderMap){
            return -2;
        }
        //订单性质 对公 对私
        String orderType = String.valueOf(orderMap.get("ORDERTYPE"));
        paramMap.put("orderType",orderType);
        //单笔最大金额限制
        BigDecimal tranddelMax1=new BigDecimal(CustomConfig.getTranddelMax());

        List<Map<String,Object>> upList = new ArrayList<>();

        //限制条件（未出款）
        paramMap.put("settle_state", 0);
        //type 0-填单、1-一键填单
        if (type==0){
            paramMap.put("ids",ids);
            upList=profitSbOrderMapper.getUnPayListById(paramMap);
        }else if (type==1){
            upList=profitSbOrderMapper.getUnPayList(paramMap);
        }
        if(upList.size() == 0){
            //不存在满足条件的出款数据
            return -2;
        }
        List<String> ableIntList = new ArrayList<>();
        for (Map<String,Object> tmp : upList){
            //判断选择的出款数据的性质（对公，对私），是否满足订单性质
            String accountType= String.valueOf(tmp.get("NATURE"));
            if (orderType.equals(accountType)){
                //校验金额是否超过二十万
                BigDecimal tmpMoney=new BigDecimal(String.valueOf(tmp.get("MONEY")));
                if (tmpMoney.compareTo(tranddelMax1) < 1){
                    //不大于二十万
                    ableIntList.add(String.valueOf(tmp.get("SETTLE_SERIAL")));
                }
            }
        }
        //更新出款数据订单号
        List<List<String>> partition = Lists.partition(ableIntList, 500);
        for (List<String> list : partition) {
            paramMap.put("ableIntList",list);
            profitSbOrderMapper.updateMerPaidOrderTwo(paramMap);
        }
        //更新订单信息
        result=profitSbOrderMapper.updateOrderInfoByDb(paramMap);
        return result;
    }

    @Override
    public Map<String, Object> getOrderOne(Map<String, Object> params) {
        return profitSbOrderMapper.getOrderOne(params);
    }

    @Override
    public List<Map<String, Object>> getUnPayListById(Map<String, Object> params) {
        return profitSbOrderMapper.getUnPayListById(params);
    }

    @Override
    public AjaxResult saveFrozen(String[] ableIds, Map<String, Object> paramMap) {
        paramMap.put("ableIds",ableIds);
        paramMap.put("settle_state",-3);//冻结
        paramMap.put("oldsettle_state",0);//条件
        String remarks="冻结原因："+paramMap.get("remarks")+",操作人："+paramMap.get("adminname")+",操作时间："+Utils.formateDate(2)+"。";
        paramMap.put("remarks",remarks);
        paramMap.put("searchType",0);
        int result=profitSbOrderMapper.updateMerPaidFrozen(paramMap);
        return  result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public List<Map<String, Object>> getOrderPageList(Map<String, Object> params) {
        return profitSbOrderMapper.getOrderPageList(params);
    }

    @Override
    public Map<String, String> auditOrder(Map orderNumber) throws Exception{
        Map<String, Object> profitSbBill = profitSbOrderMapper.auditOrderTwo(orderNumber);
        if (MapUtils.isEmpty(profitSbBill)) {
            throw new BusinessException("订单数据不存在");
        }
        Map<String, String> data = new TreeMap<String, String>();
        // 订单编号
        data.put("_orderNum", String.valueOf(profitSbBill.get("ORDERNUMBER")));
        // 订单时间
        data.put("_orderDate", String.valueOf(profitSbBill.get("INDATE")));
        // 请求时间
        data.put("_reqDate", Utils.formateDate(2));
        data.put("_signature", getSign(data));
        orderNumber.put("beForState","4");
        profitSbOrderMapper.auditOrder(orderNumber);
        return data;
    }

    @Override
    public void auditOrderError(Map params) throws Exception {
        profitSbOrderMapper.auditOrderError(params);
    }

    @Override
    public AjaxResult signSuccess(Map<String,Object> paramMap) {
        String ids=String.valueOf(paramMap.get("ids"));
        String[] serials=ids.split(",");
        List<String> list=Arrays.asList(serials);
        List<Map<String,Object>> statusList=profitSbOrderMapper.selectPaidStatusBySerial(list);
        for (Map<String, Object> map : statusList) {
            String status=String.valueOf(map.get("STATUS"));
            if (!"-1".equals(status)){
                return AjaxResult.error("非已上送付款不能标记成功");
            }
        }
        paramMap.put("status","1");
        paramMap.put("serial",serials);
        int result=profitSbOrderMapper.updateStatusToSuccessBySerial(paramMap);
        return  result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public List<Map<String, Object>> getUnpayListByOrder(Map<String, Object> params) {
        return profitSbOrderMapper.getUnpayListByOrder(params);
    }

    @Override
    public AjaxResult saveSignFail(Map<String, Object> paramMap) {
        //出款失败
        paramMap.put("settle_state",-2);
        String remarks="标记失败：原因："+paramMap.get("remarks")+",操作人："+paramMap.get("adminname")+",操作时间："+Utils.formateDate(2)+"。";
        paramMap.put("remarks",remarks);
        int result=profitSbOrderMapper.updateMerPaidFrozen(paramMap);
        return  result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public Map<String, Object> getApAc(String settleSerial) {
        return profitSbOrderMapper.getApAc(settleSerial);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult changeAccounts(Map<String, Object> map) throws Exception {
        int result = 0;
        String screen_num = map.get("S2") + "";
        map.put("show_screennum", screen_num.substring(0,6)+"****"+screen_num.substring(screen_num.length()-4));
        map.put("screen_num",EncryptUtils.getEncrypt(screen_num));
        if("0".equals(map.get("sign").toString())){//同步
            //卡包表
            profitSbOrderMapper.updateBag(map);
            //打款数据表
            profitSbOrderMapper.updatePaid(map);
            //账户表
            map.put("resphone",EncryptUtils.getEncrypt(map.get("resphone").toString()));
            result = profitSbOrderMapper.updateAcct(map);
        }else{//不同步  ------  服务商分润结算操作下 同步变更 账户 及 出款表结算卡号
            //result = profitSbOrderService.updateAcDLS(map);
            result = profitSbOrderMapper.updatePAIDDLS(map);

        }
        return  result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public List<String> getAllAgentPaidNumber(String[] ids) {
        Map map = new HashMap();
        map.put("idvalue",ids);
        return profitSbOrderMapper.getAllAgentPaidNumber(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveTransFo(Map<String, String> map) {
        String ordernumber=map.get("ordernumber");
        String idValue=map.get("idValue");
        String nownumber=map.get("nownumber");
        int result = 0;
        String [] ids = idValue.split(",");
        //获取新的流水
        HashMap tmpMap = new HashMap();
        for (String oldSerial : ids){
            //查询当前订单数据
            HashMap<String, Object> params = Maps.newHashMap();
            params.put("settle_serial",oldSerial);
            List<Map<String, Object>> data = profitSbOrderMapper.selectAgentPaidInfo(params);
            if (CollectionUtils.isNotEmpty(data)) {
                BigDecimal b = new BigDecimal("0.00");
                BigDecimal money = new BigDecimal(String.valueOf(data.get(0).get("MONEY")));
                int i = money.compareTo(b);
                if ( i == -1 || i == 0) {
                    return  AjaxResult.error("金额不可为0");
                }
            } else {
                return  AjaxResult.error("数据错误");
            }

            //生成新的流水号
            String serial=Utils.getDsettleSerial();
            tmpMap.put("newserial",serial);
            tmpMap.put("ordernumber",ordernumber);
            tmpMap.put("settle_state","0");
            tmpMap.put("oldserial",oldSerial);
            int ct=profitSbOrderMapper.updateAgentPaidData(tmpMap);
            if (ct>0){
                result++;
            }
        }
        if(result>0){
            //重新统计两个单号数据
            if (nownumber != null && nownumber.length() > 0){
                String [] oldnumber = nownumber.split(",");
                for (int i = 0;i<oldnumber.length;i++){
                    //重新统计被转单
                    Map two = new HashMap();
                    two.put("ordernumber",oldnumber[i]);
                    profitSbOrderMapper.updateCtsAgent(two);
                }
            }
            //重新统计转单
            Map three = new HashMap();
            three.put("ordernumber",ordernumber);
            three.put("afterState","3");
            three.put("beforeState","0");
            profitSbOrderMapper.updateCtsAgent(three);
        }else{
            return  AjaxResult.error("选中单号为空，请重新操作！");
        }
        return  AjaxResult.success();
    }

    @Override
    public AjaxResult saveThaw(String[] ableIds, Map<String, Object> paramMap) {
        paramMap.put("ableIds",ableIds);
        paramMap.put("settle_state",0);//解冻
        paramMap.put("oldsettle_state",0);//条件
        String remarks="解冻原因："+paramMap.get("remarks")+",操作人："+paramMap.get("adminname")+",操作时间："+Utils.formateDate(2)+"。";
        paramMap.put("remarks",remarks);
        paramMap.put("searchType",-3);
        int result=profitSbOrderMapper.updateMerPaidFrozen(paramMap);
        return result>0 ? AjaxResult.success():AjaxResult.error();
    }

    @Override
    public List<Map<String, Object>> getCallbackList(Map<String, Object> params) {
        return profitSbOrderMapper.getCallbackList(params);
    }

    @Override
    public List<Map<String, Object>> getCallbackListSum(Map<String, Object> params) {
        return profitSbOrderMapper.getCallbackListSum(params);
    }


    @Override
    @Async
    public Integer exportPayList(Map<String,Object> params) {
        List<Map<String, Object>> unPayPageList = profitSbOrderMapper.getUnPayPageList(params);
        List<AgentPaiTemplate> agentPaiTemplates = new ArrayList<>();
        for (Map<String, Object> data : unPayPageList) {
            AgentPaiTemplate agentPaiTemplate = new AgentPaiTemplate();
            agentPaiTemplate.setSettle_serial(data.get("SETTLE_SERIAL") == null ? "" : data.get("SETTLE_SERIAL").toString());
            agentPaiTemplate.setOrdernumber(data.get("ORDERNUMBER") == null ? "" : data.get("ORDERNUMBER").toString());
            agentPaiTemplate.setTop_agent_num(data.get("TOP_AGENT_NUM") == null ? "" : data.get("TOP_AGENT_NUM").toString());
            agentPaiTemplate.setTop_agent_name(data.get("TOP_AGENT_NAME") == null ? "" : data.get("TOP_AGENT_NAME").toString());
            agentPaiTemplate.setAgent_num(data.get("AGENT_NUM") == null ? "" : data.get("AGENT_NUM").toString());
            agentPaiTemplate.setAgent_name(data.get("AGENT_NAME") == null ? "" : data.get("AGENT_NAME").toString());
            agentPaiTemplate.setAuditdate(data.get("AUDITDATE") == null ? "" : data.get("AUDITDATE").toString());
            agentPaiTemplate.setProfit_type(PublicTypeUtils.getTypeStr(data.get("PROFIT_TYPE")));
            agentPaiTemplate.setCycle(PublicTypeUtils.getCycleType(data.get("CYCLE")));
            agentPaiTemplate.setScreen_name(data.get("SCREEN_NAME") == null ? "" : data.get("SCREEN_NAME").toString());
            agentPaiTemplate.setBank_name(data.get("BANK_NAME") == null ? "" : data.get("BANK_NAME").toString());
            agentPaiTemplate.setShow_screennum(data.get("SHOW_SCREENNUM") == null ? "" : data.get("SHOW_SCREENNUM").toString());
            agentPaiTemplate.setMoney(data.get("MONEY") == null ? "" : data.get("MONEY").toString());
            agentPaiTemplate.setPay_time(data.get("PAY_TIME") == null ? "" : data.get("PAY_TIME").toString());
            agentPaiTemplate.setStatus(PublicTypeUtils.getStatusType(data.get("STATUS")));
            agentPaiTemplates.add(agentPaiTemplate);
        }
        ExcelUtil<AgentPaiTemplate> util = new ExcelUtil<AgentPaiTemplate>(AgentPaiTemplate.class);
        jobTaskService.asyncDownLoad("分润付款数据",Long.parseLong("20"),"分润付款数据",params.get("ADD_MAN").toString(),agentPaiTemplates,util);
        return agentPaiTemplates.size();
    }



    private String getSign(Map<String, String> map){
        StringBuffer sb=new StringBuffer();
        sb.append("_orderNum=").append(map.get("_orderNum"));
        sb.append("&");
        sb.append("_orderDate=").append(map.get("_orderDate"));
        sb.append("&");
        sb.append("_reqDate=").append(map.get("_reqDate"));
        return Encrypt.md5(sb.toString());
    }

    public byte[] connServer(byte[] reqPack) throws Exception {
        Socket socket = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            String ipAddress = CustomConfig.getOrderCompleteUrl();
            int port = Integer.parseInt(CustomConfig.getOrderCompletePort());
            socket = new Socket(); // 建立与服务器端的链接
            socket.connect(new InetSocketAddress(ipAddress, port), 60000); // 连接超时设置
            socket.setSoTimeout(60000); // 读写超时设置
            os = socket.getOutputStream();
            is = socket.getInputStream();
            os.write(reqPack);
//			System.out.println("请求包：" + lo.byte2HexStr(reqPack));
            os.flush();
            // 接收服务器的响应
            byte[] lenByte = new byte[2];
            is.read(lenByte, 0, 2);
            int len = (int) lo.byteArrayToShort(lenByte);
            byte[] bb = new byte[len];
            is.read(bb, 0, len);
            byte[] respPack = new byte[lenByte.length + bb.length];
//			System.arraycopy(lenByte, 0, respPack, 0, 2);
//			System.arraycopy(bb, 0, respPack, lenByte.length, bb.length);
            return lo.checkByte(bb) ? null : bb;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (socket != null){
                socket.close();
            }
            if (is != null){
                is.close();
            }
            if (os != null){
                os.close();
            }
        }
    }

    public <T>  List<List<T>> getSumArrayList(List<T> list){
        List<List<T>> objectlist = new ArrayList<>();
        int iSize = list.size()/1000;
        int iCount = list.size()%1000;
        for(int i=0;i<=iSize;i++){
            List<T> newObjList = new ArrayList<>();
            if(i==iSize){
                for(int j =i*1000;j<i*1000+iCount;j++ ){
                    newObjList.add(list.get(j));
                }
            }else{
                for(int j =i*1000;j<(i+1)*1000;j++ ){
                    newObjList.add(list.get(j));
                }
            }
            if(newObjList.size()>0){
                objectlist.add(newObjList);
            }
        }
        return objectlist;
    }
}
